package com.ji.server;

import com.ji.NioConnection;
import com.ji.NioSession;
import com.ji.SessionManager;
import com.ji.protocol.JCProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Title:
 * Description:
 * Author:吉
 * Since:2017/5/19
 * Version:1.1.0
 */
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    private final String msg = "hello java world";
    private static final AtomicInteger connectionsCounter = new AtomicInteger(0);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SessionManager.create(new NioSession(new NioConnection(ctx),connectionsCounter.getAndIncrement()));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // you can use the Object from Server here

        JCProtocol  jsmsg= (JCProtocol) msg;
        System.out.println("client receive msg:" + jsmsg);
        ctx.write(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
